package com.alex.server.service.impl;

import com.alex.server.controller.LoginController;
import com.alex.server.mapper.AdminMapper;
import com.alex.server.mapper.RoleMapper;
import com.alex.server.pojo.Admin;
import com.alex.server.pojo.Menu;
import com.alex.server.pojo.Role;
import com.alex.server.service.IAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.alex.server.config.security.JwtTokenUtils;
import com.alex.server.pojo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author alex
 * @since 2022-08-30
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder pw;
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RoleMapper roleMapper;
    /**
     * 登录之后返回token
     *
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login( String username, String password, String code,HttpServletRequest request) {
        String captcha =(String) request.getSession().getAttribute("rightCode");
        if(StringUtils.isEmpty(code)|| !captcha.equalsIgnoreCase(code)){
           return RespBean.error("验证码输入错误,请重新输入!");
        }
        //登录
        UserDetails userDetails= userDetailsService.loadUserByUsername(username);
        if (userDetails== null|| !pw.matches(password,userDetails.getPassword())
         ){
            return RespBean.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()){
            return RespBean.error("账号被禁用,请联系管理员");
       }
        //跟新security登陆用户对象
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(userDetails,null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtils.generateToken(userDetails);
        Map<String,String> tokenMap=new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RespBean.success("登录成功",tokenMap);
    }

    /**
     * 根据用户名获取对象
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>()
                .eq("username",username)
                .eq("enabled",1));
    }

    /**
     * 根据
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    @Override
    public List<Admin> getAllAdmins(String keywords) {

        return  adminMapper.getAllAdmins(((Admin)SecurityContextHolder.getContext().getAuthentication().
                getPrincipal()).getId(),keywords);
    }

    @Override
    public RespBean updateAdminPassword(String oldPass, String newPass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        if (encoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(encoder.encode(newPass));
            int result = adminMapper.updateById(admin);
            if (1==result){
                return RespBean.success("更新成功");
            }else {
                return RespBean.error("更新失败");
            }
        }else {
            return RespBean.error("密码错误");
        }
    }
}
